import {
  getDelayReviewList,
  getContractList,
  getUserInfo
} from '/service/service'
import {
  getContainerHeight
} from '/utils/getDimensionUtil';
const {
  getCurrentStatusMap
} = require('/utils/statusMap')
Page({
  data: {
    searchHeight: 0,

    hasMore: true,
    windowHeight: 0,
    isLoading: false,
    scrollTop: 0,
    scrollViewHeight: 0,
    showBackTop: false,
    // 添加加载锁，防止重复触发
    loadLock: false,

    pageNum: 1,
    pageSize: 10,
    total: 0,
    currentTotal: 0,
    list: [],

    searchContent: {},
    contractName: '',
    contractNameList: [],
    contractNameListIndex: 0,
    faultLocation: '',
    roles: [],
    currentStatus: '审核通过',
    // 状态-配置映射表
    statusConfig: {
      '审核通过': {
        iconType: 'CheckCircleOutline',
        fontColor: '#00bc7d',
        bgColor: '#00bc7d33'
      },
      '审核未通过': {
        iconType: 'CloseCircleOutline',
        fontColor: '#f53f3f',
        bgColor: '#f53f3f33'
      },
      '待处理': {
        iconType: 'ExclamationCircleOutline',
        fontColor: '#000000',
        bgColor: '#00000033'
      }
    }
  },
  onLoad() {
    getUserInfo().then(res => {
      const {
        roles
      } = res
      if (roles) {
        this.setData({
          roles
        })
      }
    })
    this.getWindowHeight()
    this.getContractList()
    this.getList()
  },
  onPageScroll(e) {
    const {
      scrollTop
    } = e
    const {
      windowHeight,
      scrollViewHeight,
      isLoading,
      hasMore,
      loadLock,
      total,
      list
    } = this.data

    this.setData({
      showBackTop: scrollTop > 300
    });

    // 增加loadLock判断，防止同一时间多次触发
    if (isLoading || !hasMore || loadLock || total === 0) return

    // 优化滚动判断逻辑，确保只有当滚动到底部附近且尚未加载时才触发
    const remainingDistance = scrollViewHeight - scrollTop - windowHeight

    // 当剩余距离小于50px且当前列表长度小于总条数时才加载
    if (remainingDistance < 50 && list.length < total) {
      // 设置加载锁
      this.setData({
        loadLock: true
      })

      this.setData({
        pageNum: this.data.pageNum + 1
      }, () => {
        this.getList().then(() => {
          // 加载完成后释放加载锁
          this.setData({
            loadLock: false
          })
        })
      })
    }

    this.setData({
      scrollTop
    })
  },
  onReady() {
    this.getSearchHeight()
    this.getWrapHeight()
  },
  onShow() {
    this.handleSearch()
  },
  onPullDownRefresh() {
    this.setData({
      pageNum: 1,
      list: [],
      hasMore: true,
      loadLock: false // 重置加载锁
    }, async () => {
      try {
        await this.getList();
      } catch (e) {
        console.error('下拉刷新失败：', e);
      } finally {
        dd.stopPullDownRefresh();
      }
    });
  },
  getWindowHeight() {
    const systemInfo = my.getSystemInfoSync()
    this.setData({
      windowHeight: systemInfo.windowHeight
    })
    console.log(this.data.windowHeight)
  },
  async getList() {
    if (this.data.isLoading || !this.data.hasMore) return
    const {
      pageNum,
      pageSize,
      searchContent
    } = this.data
    const params = {
      pageNum,
      pageSize,
      ...searchContent
    }
    // console.log(params)
    try {
      this.setData({
        isLoading: true
      })
      const res = await getDelayReviewList(params)
      const {
        rows,
        total
      } = res
      const newList = rows
        .filter(r => !this.data.list.some(old => old.id === r.id))
        .map(item => {
          return {
            ...item,
            currentStatusName: getCurrentStatusMap(item.status)
          }
        })

      const updateList = this.data.list.concat(newList)
      // 更准确地判断是否还有更多数据
      const hasMore = updateList.length < total

      this.setData({
        list: updateList,
        total,
        hasMore,
        isLoading: false
      }, () => {
        this.getWrapHeight()
      })
    } catch (e) {
      this.setData({
        isLoading: false,
        loadLock: false // 出错时也要释放加载锁
      })
      my.alert({
        content: e
      })
      console.log(e)
    }
  },
  getContractList() {
    getContractList().then(res => {
      if (res.length > 0) {
        const contractNameList = ['请选择合同名称']
        res.forEach(item => {
          contractNameList.push(item.contractName)
        })
        this.setData({
          contractNameList
        })
      }
    })
  },
  async getSearchHeight() {
    const searchHeight = await getContainerHeight('.search-line-container')
    if (searchHeight) {
      this.setData({
        searchHeight
      })
    }
  },
  async getWrapHeight() {
    const scrollViewHeight = await getContainerHeight('.delayReview_container')
    if (scrollViewHeight) {
      this.setData({
        scrollViewHeight
      })
    }
  },
  backToTop() {
    my.pageScrollTo({
      scrollTop: 0,
      duration: 300
    });
    this.setData({
      showBackTop: false
    });
  },
  searchInput(e) {
    this.setData({
      faultLocation: e.detail.value,
      'searchContent.faultLocation': e.detail.value
    })
  },
  handleSearch(val) {
    const searchContent = {
      faultLocation: val ? val : null
    };

    this.setData({
      list: [],
      searchContent,
      pageNum: 1,
      pageSize: 10,
      hasMore: true,
      isLoading: false,
      loadLock: false // 重置加载锁
    }, () => {
      this.getList().then(() => {
        this.backToTop()
      })
    });
  },
  review(e) {
    const {
      item
    } = e.currentTarget.dataset
    my.navigateTo({
      url: `./audit/audit?id=${item.id}`
    })
  },
  viewDetail(e) {
    const {
      item
    } = e.currentTarget.dataset
    my.navigateTo({
      url: `/pages/detail/detail?id=${item.id}&isDelay=true&currentPage=5`
    })
  },
  handleReset() {
    this.setData({
      contractNameListIndex: 0,
      faultLocation: '',
      searchContent: {},
      list: [],
      pageNum: 1,
      pageSize: 10,
      hasMore: true,
      isLoading: false,
      loadLock: false // 重置加载锁
    }, () => {
      this.getList().then(() => {
        this.backToTop()
      });
    });
  },
  contractNameChange(e) {
    const index = e.detail.value
    this.setData({
      contractNameListIndex: index,
      contractName: this.data.contractNameList[index],
      'searchContent.contractName': index > 0 ? this.data.contractNameList[index] : null
    })
  }
});